package com.yanqu.road.dao.impl.relatives;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.relatives.RelativesGift;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RelativesGiftDaoImpl extends TempDataObjectDao<RelativesGift> {

    public Long getMaxGiftId() {
        String sql = "select ifnull(max(giftId),0) as maxId from t_u_relatives_gift";
        ResultSet rs = null;
        CallableStatement call = null;
        long maxId = 0L;
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                maxId = rs.getLong("maxId");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return maxId;
    }

    public int getDayGiveOrReceiveGiftNum(long userId, boolean isFrom) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql;
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        if (isFrom) {
            sql = "select count(*) from t_u_relatives_gift where fromId = ? and lastTime > ?";
        } else {
            sql = "select count(*) from t_u_relatives_gift where toId = ? and lastTime > ?";
        }
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            call.setLong(2, zeroTime);
            rs = call.executeQuery();
            if (rs.next()) {
                return rs.getInt(1);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return 0;
    }

    public Map<Long, RelativesGift> getRelativesGift(long userId, boolean isFrom) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, RelativesGift> dataMap = new ConcurrentHashMap<>();
        String sql;
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        if (isFrom) {
            sql = "select * from t_u_relatives_gift where fromId = ? and lastTime > ?";
        } else {
            sql = "select * from t_u_relatives_gift where toId = ? and lastTime > ?";
        }
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            call.setLong(2, zeroTime);
            rs = call.executeQuery();
            while (rs.next()) {
                RelativesGift data = parse(rs);
                if (isFrom) {
                    dataMap.put(data.getToId(), data);
                } else {
                    dataMap.put(data.getFromId(), data);
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public List<RelativesGift> getRelativesGiftList(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        List<RelativesGift> dataList = new ArrayList<>();
        String sql = "select * from t_u_relatives_gift where (fromId = ? or toId = ?) and lastTime > ?";
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i++, userId);
            call.setLong(i++, userId);
            call.setLong(i++, zeroTime);
            rs = call.executeQuery();
            while (rs.next()) {
                RelativesGift data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    public List<RelativesGift> getRelativesGiftList(List<Long> userIdList) {
        ResultSet rs = null;
        CallableStatement call = null;
        List<RelativesGift> dataList = new ArrayList<>();
        String sql = "select * from t_u_relatives_gift where (fromId in (" + StringUtils.listToString(userIdList, ",") + ") or toId in (" + StringUtils.listToString(userIdList, ",") + ")) and lastTime > ?";
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i++, zeroTime);
            rs = call.executeQuery();
            while (rs.next()) {
                RelativesGift data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    @Override
    protected boolean addData(RelativesGift data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_u_relatives_gift(giftId,fromId,toId,isGet,lastTime) values (?,?,?,?,?) ";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getGiftId());
            call.setLong(i++, data.getFromId());
            call.setLong(i++, data.getToId());
            call.setBoolean(i++, data.isGet());
            call.setLong(i++, data.getLastTime());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(RelativesGift data) {
        PreparedStatement call = null;
        String sql = "UPDATE t_u_relatives_gift SET fromId=?,toId=?,isGet=?,lastTime=? where giftId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getFromId());
            call.setLong(i++, data.getToId());
            call.setBoolean(i++, data.isGet());
            call.setLong(i++, data.getLastTime());
            call.setLong(i++, data.getGiftId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected RelativesGift parseData(ResultSet rs) throws SQLException {
        RelativesGift data = new RelativesGift();
        data.setGiftId(rs.getLong("giftId"));
        data.setFromId(rs.getLong("fromId"));
        data.setToId(rs.getLong("toId"));
        data.setGet(rs.getBoolean("isGet"));
        data.setLastTime(rs.getLong("lastTime"));
        return data;
    }
}
